import 'dart:async';
import 'dart:convert';
import 'dart:developer';

import 'package:dio/dio.dart' as dio;
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:xuance/RoutePath.dart';
import 'package:xuance/bean/exp.dart';
import 'package:xuance/bean/response_data.dart';
import 'package:xuance/network/interceptor.dart';
import 'package:xuance/util/cache_util.dart';
import 'package:xuance/util/toast_util.dart';

class NetworkService extends GetxService {
  // static String BASE_URL = "http://10.28.3.152:8003";
  // static String BASE_URL = "http://10.28.1.140:8003";
  static String BASE_URL = "http://10.28.6.144:8003";
  static final dio.Dio _dio = dio.Dio()..interceptors.add(SignInterceptor());
  static Future<ResponseData> post(
      {required String url,
      required Map<String, dynamic> map,
      loadingText = "加载中",
      bool isShowLoading = true,
      bool showErrToast = true,
      Duration? sendTimeout,
      Duration? receiveTimeout,
      useFormData = false,
      dio.CancelToken? cancelToken}) async {
    if (isShowLoading) {
      showLoading(loadingText);
    }
    var token = await CacheUtil.getToken();
    var userCode = (await CacheUtil.getUser())?.userCode;
    Map<String, dynamic> header = {"token": token, "userCode": userCode};
    try {
      log("emmmmm_url:$BASE_URL/$url");
      var res = (await _dio.post("$BASE_URL/$url",
          options: dio.Options(
            headers: header,
            followRedirects: true,
            maxRedirects: 10,
            contentType: 'application/json',
            sendTimeout: sendTimeout,
            receiveTimeout: receiveTimeout,
          ),
          data: useFormData ? dio.FormData.fromMap(map) : map,
          cancelToken: cancelToken, onSendProgress: (a, t) {
        print("发送进度:$a/$t");
      }, onReceiveProgress: (a, t) {
        print("接收进度:$a/$t");
      }));
      if (isShowLoading) {
        dismissLoading();
      }
      var data;
      if (res.data is Map) {
        data = ResponseData.fromJson(res.data);
      } else {
        data = ResponseData.fromJson(jsonDecode(res.data));
      }
      if (data.code == EXP.correct.code) {
        log("emmmmm($url)头部:${jsonEncode(header)}");
        if (!useFormData) {
          log("emmmmm($url)参数:${jsonEncode(map)}");
        }
        log("emmmmm($url)结果:${jsonEncode(data.data)}");
        return data;
      } else if (data.code == EXP.tokenExpire.code) {
        if (showErrToast) {
          showToast("登录失效");
        }
        Get.offAllNamed(RoutePath.login);
        throw ApiException(code: data.code ?? -3, message: data.message ?? "");
      } else {
        throw ApiException(code: data.code ?? 500, message: data.message ?? "");
      }
    } on ApiException catch (e) {
      dismissLoading();
      log("emmmmm($url)头部:${jsonEncode(header)}");
      if (!useFormData) {
        log("emmmmm($url)参数:${jsonEncode(map)}");
      }
      log("emmmmm($url)接口报错:${e.toJson()}");
      if (isShowLoading) {
        EasyLoading.dismiss();
      }
      if (showErrToast) {
        showToast(e.message);
      }
      rethrow;
    } on dio.DioException catch (e) {
      print(e);
      if (showErrToast) {
        showToast("请检查网络链接");
      }
      rethrow;
    } catch (e) {
      print("其他报错:$e");
      rethrow;
    }
  }
}
